﻿using Crossroad.Core.Configs;
using Crossroad.OAuth.Attributes;
using Crossroad.System.Api;
using Crossroad.System.User.Dto;
using Crossroad.System.User.Service;
using Crossroad.System.User.Service.Impl;
using Crossroad.Utils.Extensions;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Linq;
using Crossroad.System.Admin.Attributes;
using Crossroad.System.User.Model;
using Crossroad.System.Admin.Service.Impl;
using Crossroad.System.Admin.Service;

namespace Crossroad.System.User.Controller
{

    [ApiAuthorize]
    [Route("api/system/app/users")]
    public class UserAppController : BaseApi
    {
        private readonly UserAppService service;
        private readonly OrganizationService organizationService;

        public UserAppController(
            IUserAppService serviceIpt,
            IOrganizationService organizationServiceIpt
        )
        {
            service = serviceIpt as UserAppService;
            organizationService = organizationServiceIpt as OrganizationService;
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="organizationId">组织架构id</param>
        /// <param name="keywords"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="identity">身份ids</param>
        /// <returns></returns>
        [HttpGet]
        public object GetList(
            int? pageIndex = null,
            int? pageSize = null,
            int? organizationId = null,
            string keywords = "",
            string startDate = "",
            string endDate = "",
            string identity = ""
        )
        {
            var userApp = CurrentUserApp;

            if (organizationId.Contains())
            {
                var org = organizationService.GetEntity(organizationId.Value, false);
                if (org.parentId.NotContent())
                    organizationId = null;
            }

            //无分页列表查询
            if (pageIndex == null && pageSize == null)
                return service.GetList(queryable =>
                {
                    queryable.OrderBy((a) => a.createTime, OrderByType.Desc);

                    if (userApp.NotNull())
                        queryable.Where(a => a.appId.Equals(userApp.appId) && a.loginMode.Equals(userApp.loginMode));
                    if (keywords.Contains())
                        queryable.Where((a, b) => SqlFunc.Contains(b.nickName, keywords));

                    if (organizationId.Contains())
                        queryable.Where(a => a.organizationId == organizationId.Value);
                    if (startDate.Contains() && endDate.Contains())
                        queryable.Where(a => SqlFunc.Between(
                            a.createTime
                            , startDate.FillStartTime().ToDateTime().ToTimeStamp()
                            , endDate.FillEndTime().ToDateTime().ToTimeStamp()
                        )
                    );
                });

            //有分页列表查询
            pageIndex = pageIndex ?? 1;
            pageSize = pageSize ?? AppConfig.DEFAULT_PAGE_SIZE;

            return service.GetPaging(
                userApp,
                pageIndex.Value,
                pageSize.Value,
                queryable =>
                {
                    queryable.OrderBy((a) => a.createTime, OrderByType.Desc);

                    queryable.Where(a => a.userId > 1);
                    if (userApp.NotNull())
                        queryable.Where(a => a.appId.Equals(userApp.appId) && a.loginMode.Equals(userApp.loginMode));
                    if (keywords.Contains())
                        queryable.Where((a, b) => SqlFunc.Contains(b.nickName, keywords));
                    if (identity.Contains())
                        queryable.In(a => a.roleId, identity.Split(','));

                    if (organizationId.Contains())
                        queryable.Where(a => a.organizationId == organizationId.Value);
                    if (keywords.Contains())
                        queryable.Where((a, b) => SqlFunc.Contains(b.nickName, keywords));
                    if (startDate.Contains() && endDate.Contains())
                        queryable.Where(a => SqlFunc.Between(
                            a.createTime
                            , startDate.FillStartTime().ToDateTime().ToTimeStamp()
                            , endDate.FillEndTime().ToDateTime().ToTimeStamp()
                        )
                    );
                }
            );
        }

        /// <summary>
        /// 返回字典数据
        /// </summary>
        /// <param name="keywords"></param>
        /// <returns></returns>
        [HttpGet("dic")]
        public object GetDic(
            string keywords = ""
        )
        {
            var userApp = CurrentUserApp;
            var list = service.GetList(queryable =>
             {
                 queryable.OrderBy((a) => a.createTime, OrderByType.Desc);
                 queryable.Where(a => a.userId > 1);
                 if (userApp.NotNull())
                     queryable.Where(a => a.appId.Equals(userApp.appId) && a.loginMode.Equals(userApp.loginMode));
                 if (keywords.Contains())
                     queryable.Where((a, b) => SqlFunc.Contains(b.nickName, keywords) || SqlFunc.Contains(b.phone, keywords));
             });

            return list.Select(f => new {label = $"{f.nickName} {f.phone}", value = f.id}).ToList();
        }

        /// <summary>
        /// 新增一个用户
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [HttpPost]
        public object CreateAt(
            [FromBody] UserInfoDto parameter
        )
        {
            var userApp = CurrentUserApp;
            parameter.creatorId = CurrentUser.id;
            var model = new UserApp
            {
                user = parameter,
                roleId = parameter.roleId.Value,
                organizationId = parameter.organizationId.Value,
                loginMode = userApp.loginMode,
                appId = userApp.appId,
                creatorId = CurrentUser.id,
            };
            model = service.CreateAt(model);

            return model.user;
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [HttpPatch("{uniqueKey}")]
        public object UpdateAt(
            string uniqueKey,
            [FromBody] UserInfoDto parameter
        )
        {
            var userApp = CurrentUserApp;
            var model = new UserApp
            {
                user = parameter,
                appId = userApp.appId,
                userId = parameter.id,
                roleId = parameter.roleId ?? 0,
                organizationId = parameter.organizationId.Value,
            };
            model = service.UpdateAt(model);

            return model.user;
        }


        /// <summary>
        /// 删除一个用户
        /// </summary>
        /// <param name="key"></param>
        [HttpDelete("{userId}")]
        public object DeleteAt(int userId)
        {
            var userApp = CurrentUserApp;
            service.DeleteAt(new UserApp()
            {
                appId = userApp.appId,
                userId = userId,
            });

            return true;
        }

    }
}